package com.example.fresh_fruit.service.Impl;

import com.example.fresh_fruit.dto.OrderDto;
import com.example.fresh_fruit.entity.Commodity;
import com.example.fresh_fruit.entity.OrderDetails;
import com.example.fresh_fruit.mapper.CommodityMapper;
import com.example.fresh_fruit.mapper.OrdersDetailsMapper;
import com.example.fresh_fruit.mapper.OrdersMapper;
import com.example.fresh_fruit.service.OrderDtoService;
import com.example.fresh_fruit.util.RandomMath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;

/**
 * @author :飞天の鱼
 * @date : 2022/8/22 16:18
 */
@Service
public class OrderDtoServiceImpl implements OrderDtoService {
    private Calendar calendar = Calendar.getInstance();
    private int currentNo = 0;
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersDetailsMapper ordersDetailsMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    //计算日期
    private synchronized String getOrderNo(){
        Calendar nowCal = Calendar.getInstance();
        if(nowCal.get(Calendar.DAY_OF_YEAR)!= calendar.get(Calendar.DAY_OF_YEAR)){
            currentNo = 0;
            calendar = nowCal;
        }
        //订单号的拼接--> DD%04d%02d%02d%04d --> DD年月日+
        return String.format("DD%04d%02d%02d%04d",
                calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH) + 1,calendar.get(Calendar.DATE),++currentNo);
    }

    @Override
    public int insertOrder(OrderDto orderDto) {
        orderDto.setOrderNo(getOrderNo());
        int insertOders = ordersMapper.insertOders(orderDto);
        if (insertOders>0){
            //向订单详情中插入数据
            List<OrderDetails> detailsList = orderDto.getOrderDetailsList();
            for (OrderDetails orderDetails:detailsList) {
                orderDetails.setOrderId(orderDto.getId());
                ordersDetailsMapper.insertOrderDetails(orderDetails);
            }
        }
        return 0;
    }


}
